package com.lemo.juc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Producer$ConsumerDemo {
	public static void main(String[] args) {
		Clerk clerk = new Clerk();
		Producer producer = new Producer(clerk);
		Consumer consumer = new Consumer(clerk);

		new Thread(producer, "生产者A").start();

		new Thread(consumer, "消费者B").start();
		
		new Thread(producer, "生产者C").start();

		new Thread(consumer, "消费者D").start();
	}
}

class Clerk {
	private int product = 0;

	private Lock lock = new ReentrantLock();
	private Condition newCondition = lock.newCondition();

	// 进货
	public void get() {

		lock.lock();
		try {
			while (product >= 1) {
				System.out.println("已满");
				try {
					newCondition.await();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			System.out.println(Thread.currentThread().getName() + ":" + ++product);
			
			newCondition.signalAll();
		} finally {
			lock.unlock();
		}

	}

	// 卖货
	public void sal() {
		lock.lock();
		
		try {
			while (product <= 0) {
				System.out.println("缺货");
				try {
					//this.wait();
					newCondition.await();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			System.out.println(Thread.currentThread().getName() + ":" + --product);
			//this.notifyAll();
			newCondition.signalAll();
		} finally {
			lock.unlock();
		}
		

	}
}

class Producer implements Runnable {
	private Clerk clerk;

	public Producer() {
		super();
	}

	public Producer(Clerk clerk) {
		this.clerk = clerk;
	}

	@Override
	public void run() {
		for (int i = 0; i < 20; i++) {
			try {
				Thread.sleep(200);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			clerk.get();
		}
	}

}

class Consumer implements Runnable {

	private Clerk clerk;

	public Consumer(Clerk clerk) {
		this.clerk = clerk;
	}

	@Override
	public void run() {
		for (int i = 0; i < 20; i++) {
			clerk.sal();
		}
	}

}
